<?php
class AuthController extends Controller
{
	public function actionLogin()
	{
		if (!Yii::app()->user->isGuest){
			$this->redirect(Yii::app()->request->baseUrl);
		}
					
		//do login
		if(Yii::app()->request->isPostRequest)
		{
			$email = Yii::app()->request->getPost('email', null);
			$password = Yii::app()->request->getPost('password', null);	
			//check valid email?			
			if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
				Yii::app()->user->setFlash('error', Yii::t('helpdesk', 'Login failed because email or password is incorrect'));
			}
			//authenticate
			try{
				$identity=new UserIdentity($email, $password);
				if($identity->authenticate()){
					//login successfully, Keep the user logged in for 1 hours (Make sure allowAutoLogin is set true for the user component)
					Yii::app()->user->login($identity, 3600);
					
					//write log
					Logs::getInstance()->insert(array(
						'user_id' => Yii::app()->user->id,
						'user_ip' => Utils::getIp(),
						'user_agent' => $_SERVER['HTTP_USER_AGENT'],
						'log_action' => 'HELPDESK_LOGIN',
						'log_message' => '<b>'.Yii::app()->user->getState('fullname').'</b> logged in'
					));
					
					//redirect
					$redirectUrl = urldecode(Yii::app()->request->getParam('url', null));
					if(empty($redirectUrl)) $redirectUrl = Yii::app()->request->baseUrl;
					$this->redirect($redirectUrl);
					exit;
				}
				else{
					//write log
					Logs::getInstance()->insert(array(
						'user_id' => null,
						'user_ip' => Utils::getIp(),
						'user_agent' => $_SERVER['HTTP_USER_AGENT'],
						'log_action' => 'HELPDESK_LOGIN',
						'log_message' => '<b>'.$email.'</b> (IP: '.Utils::getIp().') login fail'
					));
					
					//wrong credentials 
					Yii::app()->user->setFlash('error', Yii::t('helpdesk', 'Login failed because email or password is incorrect'));
					
					//refresh
					$this->refresh();
					exit;
				}
			} catch (Exception $ex){
				Yii::app()->user->setFlash('error', Yii::t('helpdesk', $ex->getMessage()));
				$this->refresh();
			}
		}
		//render layout
		$this->render('login');
	}
	
	public function actionRegister(){
		if (!Yii::app()->user->isGuest){
			$this->redirect(Yii::app()->request->baseUrl);
		}
		//do register
		if(Yii::app()->request->isPostRequest){
			try{
				$args = array(
					'user_username' => trim(Yii::app()->request->getPost('email', null)),
					'user_email' => trim(Yii::app()->request->getPost('email', null)),
					'user_password' => Yii::app()->request->getPost('password', null),
					'user_fullname' => trim(Yii::app()->request->getPost('fullname', null)),
					'user_status' => 1
				);
				//TODO: CHECK EMAIL
				//create user
				$userId = Users::getInstance()->insert($args);
				if($userId){
					//create profile
					Users::getInstance()->insertProfile($userId, array(
						'profile_email' => $args['user_username'],
						'profile_phone' => trim(Yii::app()->request->getPost('phone', null)),
						'profile_address' => trim(Yii::app()->request->getPost('address', null)),
						'profile_allow_notify' => 1,
						'profile_status' => 1
					));
					//add user to deafault role (members)
					Roles::getInstance()->updateUserRole($userId, 3);
					//done
					Yii::app()->user->setFlash('ok', "Your account has been created successfully! Please login to continue");
				} else {
					Yii::app()->user->setFlash('error', "An error has occurred. Please contact your system administrator");
				}
				$this->redirect('/auth/login'); exit;
			} catch (Exception $ex){
				Yii::app()->user->setFlash('error', "Sorry, this email already exists. Please choose another one or login to continue");
				$this->refresh();
			}
		}
		//render layout
		$this->render('register');
	}
	
	public function actionLogout(){
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->request->baseUrl);
	}	
	
	public function actionForget(){
		if (!Yii::app()->user->isGuest){
			$this->redirect(Yii::app()->request->baseUrl);
		}
		
		if(Yii::app()->request->isPostRequest){
			//get params
			$email = Yii::app()->request->getPost('email', null);			
			//get user info
			$user = Users::getInstance()->getByUsername($email);
			if(empty($user)){
				Yii::app()->user->setFlash('error', Yii::t('helpdesk', 'Email doesn\'t exist'));
				$this->refresh(); exit;	
			}
			$token = Users::getInstance()->getToken($user);
			$tokenUrl = BASE_URL.'/auth/reset/?token='.$token;
			
			HelpDesk::getInstance()->sendmail('forget-password', array(
				'token' => $token,
				'token_url' => $tokenUrl,
				'user' => $user
			));
			Yii::app()->user->setFlash('ok', Yii::t('helpdesk', "We sent you an email with link that allows to change your password"));
			$this->refresh();
		}
		//render layout
		$this->render('forget');	
	}
	
	public function actionReset(){
		if (!Yii::app()->user->isGuest){
			$this->redirect(Yii::app()->request->baseUrl);
		}
		$token = Yii::app()->request->getParam('token', null);
		//check token
		if(empty($token) || USER_TOKEN_OK != Users::getInstance()->validateToken($token, DEFAULT_USER_TOKEN_EXPIRATION, $decodedToken)){			
			$this->forward('/404.html'); die;
		}
		//update password
		if(Yii::app()->request->isPostRequest){
			try{
				$password = Yii::app()->request->getParam('password', null);
				$re_password = Yii::app()->request->getParam('re_password', null);
				if($password != '' && strlen($password) >= 5 && $password == $re_password){
					Users::getInstance()->updatePassword($decodedToken['key'], $password);
					/*change secrect key to expire token*/
					Users::getInstance()->updateSecretKey($decodedToken['key']);
					Yii::app()->user->setFlash('ok', "Password has been changed. Now you can login with your new password");
					$this->redirect('/auth/login'); exit;
				}
				
			} catch (Exception $ex){
				Yii::app()->user->setFlash('error', "Sorry, this email already exists. Please choose another one or login to continue");
				$this->refresh();
			}
			
		}
		//render layout
		$this->render('reset');
	}
}